package com.thinkcar.gateway.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.thinkcar.core.exception.extension.CommonException;
import com.thinkcar.gateway.enums.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;


//@Configuration
@Slf4j
public class SaTokenConfigure {

    private static final Logger LOGGER = LoggerFactory.getLogger(SaTokenConfigure.class);

    @Bean
    public SaReactorFilter getSaServletFilter() {
        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")
                // 开放地址
                .addExclude(
                        // 静态资源
                        "/favicon.ico",
                        "/robots.txt",
                        "/static/**",
                        "/assets/**",
                        // 认证相关
                        "/demo/auth/login",
                        "/demo/auth/logout",
                        "/demo/auth/register",
                        "/demo/auth/captcha",
                        // 文档接口
                        "/doc.html",
                        "/doc.html/**",
                        "/webjars/**",
                        "/v3/api-docs",
                        "/v3/api-docs/**",
                        "/v3/api-docs/swagger-config",
                        "/*/v3/api-docs/default",
                        // Swagger UI
                        "/swagger-ui/**",
                        "/swagger-ui.html",
                        "/swagger-resources/**",
                        "/swagger-resources/configuration/ui",
                        "/swagger-resources/configuration/security",
                        // 健康检查
                        "/actuator/health",
                        "/actuator/info",
                        // 错误处理
                        "/error",
                        "/error/**"
                )
                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    // 获取当前请求对象
                    SaRequest saRequest = SaHolder.getRequest();
                    // 获取完整URL（包含协议、域名、路径和参数）
                    String fullUrl = saRequest.getUrl();
                    // 打印日志（实际项目使用日志框架）
                    log.debug("完整URL:{} ", fullUrl);
                    // 登录校验 -- 拦截所有路由，并排除/demo/auth/login用于开放登录
                    SaRouter.match("/**").check(r -> StpUtil.checkLogin());
                    // 权限认证 -- 不同模块, 校验不同权限
                    SaRouter.match("/demo/**", r -> StpUtil.checkPermission("demo"));
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e -> {
                            // 设置错误返回格式为JSON
                            ServerWebExchange exchange = SaReactorSyncHolder.getExchange();
                            exchange.getResponse().getHeaders().set("Content-Type", "application/json; charset=utf-8");
                            log.error("权限异常：", e);
                            throw new CommonException(ExceptionEnum.AUTH_ERROR);
                        }
                )
                .setBeforeAuth(obj -> {
                    // ---------- 设置跨域响应头 ----------
                    SaHolder.getResponse()
                            // 允许指定域访问跨域资源
                            .setHeader("Access-Control-Allow-Origin", "*")
                            // 允许所有请求方式
                            .setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
                            // 有效时间
                            .setHeader("Access-Control-Max-Age", "3600")
                            // 允许的header参数
                            .setHeader("Access-Control-Allow-Headers", "*");

                    // 如果是预检请求，则立即返回到前端
                    SaRouter.match(SaHttpMethod.OPTIONS).free(r -> LOGGER.info("--------OPTIONS预检请求，不做处理")).back();
                });
    }

}

